import 'package:common_utils/common_utils.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';

/// 网路状态
enum NetState {
  /// WiFi: Device connected via Wi-Fi
  wifi,

  /// Mobile: Device connected to cellular network
  mobile,

  /// None: Device not connected to any network
  none
}

class NetUtils {
  static Future<bool> isConnected() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    return connectivityResult != ConnectivityResult.none;
  }

  ///获取网络状态
  static Future<NetState> getNetState() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    switch (connectivityResult) {
      case ConnectivityResult.mobile:
        return NetState.mobile;
      case ConnectivityResult.wifi:
        return NetState.wifi;
      default:
        return NetState.none;
    }
  }

  /// IP：https://www.ip.cn/api/index?ip=&type=0
  /// {
  ///     "rs": 1,
  ///     "code": 0,
  ///     "address": "中国  广东省 广州市 电信",
  ///     "ip": "116.22.52.125",
  ///     "isDomain": 0
  /// }
  /// 淘宝：https://www.taobao.com/help/getip.php
  /// ipCallback({ip:"116.22.52.125"})
  static final dio = Dio();

  static Future<String> getPublicNetIp() async {
    LogUtil.v("GET====>https://www.ip.cn/api/index?ip=&type=0");
    var response = await dio.get("https://www.ip.cn/api/index?ip=&type=0");
    LogUtil.v(response.data);
    LogUtil.v("GET<====https://www.ip.cn/api/index?ip=&type=0");
    Map<String, dynamic> map = response.data;
    String ip = map["ip"];
    if (!TextUtil.isEmpty(ip)) return ip;
    LogUtil.v("GET====>https://www.taobao.com/help/getip.php");
    response = await dio.get("https://www.taobao.com/help/getip.php");
    LogUtil.v(response.data);
    LogUtil.v("GET<====https://www.taobao.com/help/getip.php");
    String data = response.data;
    if (!TextUtil.isEmpty(data)) {
      ip = data.substring(data.indexOf("\"") + 1, data.lastIndexOf("\""));
      if (!TextUtil.isEmpty(ip)) return ip;
    }
    return "127.0.0.1";
  }
}
